var express = require('express');
var router = express.Router();
const { Brand } = require('../../models');
const { success, fail } = require('../../utils/response');
const { getBrand } = require('../../utils/get-data');

router.get('/', async function(req, res, next) {
  try{
    let {page = 1, limit = 10} = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const offset = (page - 1) * limit;
    const {count, rows: brands} = await Brand.findAndCountAll({
      offset,
      limit,
    });
    const data = {
      data: brands,
      total: count,
      page,
      limit
    }
    success(res, data, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.get('/:id', async function(req, res, next) {
  try{
    const brand = await getBrand(req, res, next);
    success(res, brand, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.get('/seriesById/:id', async function(req, res, next) {
  try{
    let {page = 1, limit = 10} = req.query
    page = parseInt(page)
    limit = parseInt(limit)
    const offset = (page - 1) * limit
    const brand = await getBrand(req, res, next);
    const series = await brand.getSeries({
      limit,
      offset,
      joinTableAttributes: []
    })
    const count = await brand.countSeries()
    success(res, {
      data: series,
      count,
      limit,
      page
    }, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.post('/', async function(req, res, next) {
  try{
    const {nameZh, nameEn, img, descriptionZh, descriptionEn} = req.body;
    const brand = await Brand.create({nameZh, nameEn, img, descriptionZh, descriptionEn});
    success(res, brand, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.put('/:id', async function(req, res, next) {
  try{
    const {nameZh, nameEn, img, descriptionZh, descriptionEn} = req.body;
    const brand = await getBrand(req, res, next);
    await brand.update({ nameZh, nameEn, img, descriptionZh, descriptionEn});
    success(res, brand, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.delete('/:id', async function(req, res, next) {
  try{
    const brand = await getBrand(req, res, next);
    await brand.destroy();
    success(res, null, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
module.exports = router;